import React, { useState } from 'react'
import { useParams } from 'react-router-dom'
import { Layout, Card, Button, message, Modal, Pagination, Empty } from 'antd'
import RiderHeader from './components/RiderHeader'
import { $api } from '@/http/api'
import Moment from 'react-moment'
import StatusTag from '@/components/StatusTag'

const withRouter = (Component) => {
  return (props) => (
    <Component {...props} params={useParams()} />
  )
}

const { Header, Content } = Layout

const RiderButton = (props) => {
  const [isModalVisible, setIsModalVisible] = useState(false);

  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const deliver = () => {
    $api.rider.deliver({
      id: props.id
    }).then(res => {
      if (res.code === 200) {
        message.success('Successfully get the package')
        props.refresh()
      }
    }).finally(() => {
      setIsModalVisible(false)
    })
  }

  const arrive = () => {
    $api.rider.arrive({
      id: props.id
    }).then(res => {
      if (res.code === 200) {
        message.success('Successfully deliver the package')
        props.refresh()
      }
    }).finally(() => {
      setIsModalVisible(false)
    })
  }

  if (props.status === 2) {
    return (
      <>
        <StatusTag status={props.status} />
        <Button type="primary" onClick={showModal}>Get</Button>
        <Modal title="Get it" visible={isModalVisible} onOk={deliver} onCancel={handleCancel}>
          <div className='text-item'>🧑 {props.userInfo.nickname} 📞 {props.phone} ⏰ <Moment format="YYYY-MM-DD HH:mm">{props.estimatedTime}</Moment></div>
          <div className='text-item'>🥡 {props.restaurantAddress}</div>
          <div className='text-item'>🏠 {props.address}</div>
        </Modal>
      </>
    )
  } else if (props.status === 3) {
    return (
      <>
        <StatusTag status={props.status} />
        <Button type="primary" onClick={showModal}>Arrive</Button>
        <Modal title="Arrive" visible={isModalVisible} onOk={arrive} onCancel={handleCancel}>
          <div className='text-item'>🧑 {props.userInfo.nickname} 📞 {props.phone} ⏰ <Moment format="YYYY-MM-DD HH:mm">{props.estimatedTime}</Moment></div>
          <div className='text-item'>🥡 {props.restaurantAddress}</div>
          <div className='text-item'>🏠 {props.address}</div>
        </Modal>
      </>
    )
  }
}

class Rider extends React.Component {
  state = {
    pageNum: 1,
    pageSize: 12,
    total: 0,
    info: {
      nickname: 'Trump'
    },
    list: [],
  }

  componentDidMount() {
    $api.rider.getRiderInfo().then(res => {
      if (res.code === 200) {
        this.setState({
          info: res.data
        })
      }
    })
    this.refresh();
  }

  refresh = () => {
    $api.rider.getMyOrders({
      page_num: this.state.pageNum,
      page_size: this.state.pageSize
    }).then(res => {
      if (res.code === 200) {
        this.setState({
          list: res.data.list,
          total: res.data.total,
        })
      }
    })
  }

  pageChange = (page) => {
    this.setState({ pageNum: page })
    this.refresh()
  }

  render() {
    let list = null
    if (this.state.list.length === 0) {
      list = <Empty description="There is no order." className='pt-8' />
    } else {
      list =
        <>
          <div className='p-4 grid gap-4 grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4'>
            {this.state.list.map((item, index) => {
              return (
                <Card size="small" key={index} title={item.userInfo.nickname} extra={<RiderButton {...item} refresh={this.refresh} />}>
                  <div className='text-item'>🥡 {item.restaurantAddress}</div>
                  <div className='text-item'>🏠 {item.address}</div>
                  <div className='text-item'>📞 {item.phone}</div>
                  <div className='text-item'>⏰ <Moment format="YYYY-MM-DD HH:mm">{item.estimatedTime}</Moment></div>
                </Card>
              )
            })}
          </div>
          <Pagination
            style={{ textAlign: 'center', marginTop: '2rem' }}
            defaultCurrent={1}
            total={this.state.total}
            PageSize={this.state.pageSize}
            onChange={this.pageChange}
          />
        </>
    }

    return (
      <Layout className='!min-h-screen'>
        <Header className='!h-[96px] !leading-[96px] !bg-white !px-0'>
          <RiderHeader name={this.state.info.nickname}></RiderHeader>
        </Header>
        {list}
      </Layout>
    )
  }
}

export default withRouter(Rider)